<?php

namespace Payment\Common\Hsq;

use Payment\Common\BaseData;
use Payment\Common\BaseStrategy;
use Payment\Common\PayException;
use Payment\Common\HsqTransConfig;
use Payment\Utils\BaoFooRsaUtil;
use Payment\Utils\Curl;
use Payment\Utils\DataParser;


abstract class HsqTransBaseStrategy implements BaseStrategy
{

    protected $config;

    /**
     * 支付数据
     * @var BaseData $reqData
     */
    protected $reqData;

    /**
     * FuBaseStrategy constructor.
     * @param array $config
     * @throws PayException
     */
    public function __construct(array $config)
    {
        /* 设置内部字符编码为 UTF-8 */
//        mb_internal_encoding("UTF-8");
        try {
            $this->config = new HsqTransConfig($config);
        } catch (PayException $e) {
            throw $e;
        }
    }

    /**
     * 发送请求
     * @param array $body
     * @return mixed
     * @throws PayException
     */
    protected function sendReq($body)
    {
        $url = $this->getReqUrl();
        if (is_null($url)) {
            throw new PayException('目前不支持该接口。请联系开发者添加');
        }

        $body = http_build_query($body);
        if (empty($body)) throw new PayException('支付数据异常');

        $response = $this->curlPost($body, $url);
        if ($response['error']) throw new PayException('网络发生错误，请稍后再试curl返回码：' . $response['message']);

        $retData = $response['body'];
        if(count(explode("trans_content",$retData))>1){
            $retData = json_decode($retData);
            $result = $retData->trans_content->trans_head;
            if(!empty($result->return_code)) throw new PayException('支付平台返回错误提示:' . $result->return_msg);
        }
        return $retData;
    }

    /**
     * 请求
     * @param $body
     * @param $url
     * @return array
     */
    protected function curlPost($body, $url)
    {
        $curl = new Curl();
        $header = [
            'content-type: application/x-www-form-urlencoded'
        ];
        return $curl->set([
            'CURLOPT_HEADER' => 0,
            'CURLOPT_HTTPHEADER' => $header,
        ])->post($body)->submit($url, false);
    }

    /**
     * 获取请求地址
     * @param null $url
     * @return string
     */
    protected function getReqUrl($url = null)
    {
        return $this->config->base_url . ($url ?? HsqTransConfig::PAY_URL);
    }

    /**
     * @param array $data
     *
     * @throws PayException
     * @throws \Exception
     * @return array|string
     */
    public function handle(array $data)
    {
        $buildClass = $this->getBuildDataClass();
        $this->reqData = new $buildClass($this->config, $data);
        $this->reqData->setSign();
        $body = $this->reqData->getData();
        $ret = $this->sendReq($body);
        $flag = $this->verifySign($ret);
        if (!$flag) {
            throw new PayException('返回数据被篡改。请检查网络是否安全！');
        }
        return $this->retData($flag);
    }

    /**
     * 处理返回值并返回给客户端
     * @param array $ret
     * @return mixed
     *
     */
    protected function retData(array $ret)
    {
        return $ret;
    }

    /**
     * 签名验证
     * @param array $retData
     * @return bool
     * @throws PayException
     */
    protected function verifySign(string $retData)
    {
        //解密
        $decrypt = BaoFooRsaUtil::decryptByCERFile($retData, $this->reqData->publicKey);
        $result = json_decode($decrypt,true);
        return $result;

    }

}
